package com.uchedao.vehicledetection.view;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.mybaselibrary.http.VolleyUtil;
import com.uchedao.mybaselibrary.view.dialog_for_ios.ZAlertDialog;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.activity.CheckCarActivity;
import com.uchedao.vehicledetection.activity.MainActivity;
import com.uchedao.vehicledetection.config.Api;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.loadstate.UCheDaoRelativeLayout;
import com.uchedao.vehicledetection.model.BaseInfo;
import com.uchedao.vehicledetection.model.Condition;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.VinCarInfor;
import com.uchedao.vehicledetection.model.response.FastCheckCarResponse;
import com.uchedao.vehicledetection.network.HttpRequest;
import com.uchedao.vehicledetection.network.VinCarRequest;
import com.uchedao.vehicledetection.utils.JudgeUtil;
import com.uchedao.vehicledetection.utils.ProgressDialogUtil;
import com.uchedao.vehicledetection.utils.ToastUtil;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.view.carlist.CarDbUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 直接验车
 */
public class FastCheckCarView extends UCheDaoRelativeLayout {
    public static final String URL_VIN = "vehicle.vin";
    private EditText mNameEt, mPhoneEt, mCardEt, mVinEt;
    private Button mCommit;
    private boolean isOKVin;

    private boolean isEdit = true;

    private boolean isCreate = false;

    public FastCheckCarView(Context context) {
        super(context);
    }

    public FastCheckCarView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FastCheckCarView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.view_fast_check_car, this);
        mNameEt = (EditText) findViewById(R.id.view_fast_check_name_et);
        mPhoneEt = (EditText) findViewById(R.id.view_fast_check_phone_et);
        mCardEt = (EditText) findViewById(R.id.view_fast_check_card_et);
        mVinEt = (EditText) findViewById(R.id.view_fast_check_vin_et);
        mCommit = (Button) findViewById(R.id.view_fast_check_commit_btn);

    }

    public void clear() {
        isEdit = false;
        mCardEt.setText("");
        mVinEt.setText("");
        mPhoneEt.setText("");
        mNameEt.setText("");
        isEdit = true;
    }

    @Override
    public void initDataAfterView() {
//        暂时伪造数据
//        mNameEt.setText("优车到");
//        mPhoneEt.setText("15659378419");
//        mCardEt.setText("闽A56341");
//        mVinEt.setText("LFPM4ACC1E1A04502");
    }

    @Override
    public void initListener() {
        mCommit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCreate) {
                    ToastUtil.showToast("正在创建草稿", true);
                    return;
                }
                if (check()) {
                    ProgressDialogUtil.showProgressDlg(mContext, "正在创建草稿……");
                    isCreate = true;
                    getCarIdHttp(mNameEt.getText().toString().trim(), mPhoneEt.getText().toString().trim(),
                            mVinEt.getText().toString().trim(), mCardEt.getText().toString().trim());
                }
            }
        });

        mVinEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!isEdit) {
                    return;
                }
                // VIN长度不足
                if (charSequence == null || charSequence.length() != 17) {
                    isOKVin = false;
                    mVinEt.setError(mContext.getString(R.string.car_vin_pattern_combination_error));
                } else {
                    isOKVin = true;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mCardEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!isEdit) {
                    return;
                }
                String carPlant = charSequence.toString();

                if (TextUtils.isEmpty(carPlant) || !Util.isCarPlateValid(carPlant)) {
                    mCardEt.setError(mContext.getString(R.string.card_ok_error));
                } else {

                    final Draft temp = GlobalInfo.dbHelper.getDraft(charSequence.toString());
                    if (temp != null) {

                        ZAlertDialog.Builder dialog = new ZAlertDialog.Builder(mContext);

//                    CustomDialog dialog = new CustomDialog(DraftActivity.this);
                        dialog.setTitle(R.string.prompt);
                        dialog.setMessage(R.string.open_draft_msg);
                        dialog.setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                GlobalInfo.draft = temp;
                                mContext.startActivity(new Intent(mContext, MainActivity.class));


                            }
                        });
                        dialog.setNegativeButton(R.string.cancel, null);
                        dialog.show();
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private boolean check() {

        if (TextUtils.isEmpty(mNameEt.getText().toString().trim())) {
            ToastUtil.showToast("车主姓名不能为空", true);
            return false;
        }

        if (!JudgeUtil.isMobileNO(mPhoneEt.getText().toString().trim())) {
            ToastUtil.showToast("请输入正确的手机号码", true);
            return false;
        }

        String carPlate = mCardEt.getText().toString().trim();
        // 车牌
        if (TextUtils.isEmpty(carPlate)) {
            ToastUtil.showToast("请输入车牌号", true);
            return false;
        }

        // 车牌号无效
        if (!Util.isCarPlateValid(carPlate)) {
            ToastUtil.showToast("请输入有效车牌号", true);
            return false;
        }

        // VIN长度不足
        if (!isOKVin) {
            ToastUtil.showToast("请输入17位数字、字母组成的VIN码", true);
            return false;
        }

        return true;
    }

//    private void CheckHasCarPlate(String vin) {
//
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("vin", vin);
//
//        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.VIN_CHECK, params,
//                new Response.Listener<JsonObject>() {
//                    @Override
//                    public void onResponse(JsonObject response) {
//
//                    }
//                }, new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//                        ToastUtil.showToast(error.getMessage(), false);
//                    }
//                });
//        VolleyUtil.getInstance(mContext).getRequestQueue(mContext).add(req);
//
//    }

    private void getCarIdHttp(String real_name, String mobile, final String vin, final String car_number) {

        Map<String, String> params = new HashMap<String, String>();
        params.put("real_name", real_name);
        params.put("mobile", mobile);
        params.put("vin", vin);
        params.put("car_number", car_number);

        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.FAST_CHECK_CAR, params,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        FastCheckCarResponse entity = new Gson().fromJson(response, FastCheckCarResponse.class);
                        saveRecord(car_number, vin, entity.getId());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //测试专用
                        //saveRecord(car_number, vin, "23651");
                        isCreate = false;
                        ProgressDialogUtil.dismissProgressDlg();
                        ToastUtil.showToast(error.getMessage(), false);
                    }
                });
        VolleyUtil.getInstance(mContext).getRequestQueue(mContext).add(req);

    }

    private void getCarMsgByVin(String vin) {

        Map<String, String> params = new HashMap<String, String>();

        String url = CarDbUtil.getUrl(URL_VIN, "&vin=" + vin);

        Request req = new VinCarRequest(params, url,
                new Response.Listener<VinCarInfor[]>() {
                    @Override
                    public void onResponse(final VinCarInfor[] data) {

                        // 没有相应的车型信息
                        if (data == null || data.length == 0) {
//                            ToastUtil.showToastLong(R.string.get_vin_message_no);
                            return;
                        }

                        // 只有唯一数据
                        if (data.length == 1) {
                            setCarInfoFromVin(data[0]);
                            return;
                        }

                        // 当有多个车辆信息时，让用户选择

                        // 车辆信息标题
                        String[] carInfoLabels = new String[data.length];
                        for (int i = 0; i < data.length; i++)
                            carInfoLabels[i] = data[i].brand_caption;

                        // 显示选择对话框
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

                        builder.setTitle(R.string.get_vin_message_dialog_title)
                                .setItems(carInfoLabels, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        setCarInfoFromVin(data[which]);
                                    }
                                }).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                setCarInfoFromVin(null);
            }
        });

        CheckCarActivity activity = (CheckCarActivity) mContext;
        activity.addQueue(req);
    }

    /**
     * 通过Vin设置车辆信息
     *
     * @param vinCarInfo
     */
    private void setCarInfoFromVin(VinCarInfor vinCarInfo) {
        Intent intent = new Intent(mContext, MainActivity.class);
        if (vinCarInfo != null) {
//            intent.putExtra(MainActivity.VINCARINFOR, vinCarInfo);
            //车型车系信息
            GlobalInfo.draft.base_info.use_info.brand_id = Integer.parseInt(vinCarInfo.brand_id);
            GlobalInfo.draft.base_info.use_info.series_id = Integer.parseInt(vinCarInfo.series_id);
            GlobalInfo.draft.base_info.use_info.model_id = Integer.parseInt(vinCarInfo.model_id);
            GlobalInfo.draft.base_info.use_info.brand_str = vinCarInfo.brand_caption;
            GlobalInfo.draft.base_info.use_info.model_str = "";
            GlobalInfo.draft.base_info.use_info.series_str = "";

            //配置功能信息
            GlobalInfo.draft.condition.config_info.abs = vinCarInfo.abs;
            GlobalInfo.draft.condition.config_info.airbag = vinCarInfo.airbag;
            GlobalInfo.draft.condition.config_info.leather_seats = vinCarInfo.leather_seats_caption;
            GlobalInfo.draft.condition.config_info.electrically_window = vinCarInfo.electrically_window_caption;
            GlobalInfo.draft.condition.config_info.window = vinCarInfo.window_caption;
            GlobalInfo.draft.condition.config_info.gps_navigator = vinCarInfo.gps_navigator_caption;
            GlobalInfo.draft.condition.config_info.booster_type = vinCarInfo.booster_type_caption;
            GlobalInfo.draft.condition.config_info.electrically_seat = vinCarInfo.electrically_seat_caption;
            GlobalInfo.draft.condition.config_info.air = vinCarInfo.air_caption;
            GlobalInfo.draft.condition.config_info.auto_adapt_drive = vinCarInfo.auto_adapt_drive_caption;
            GlobalInfo.draft.condition.config_info.back_mirror_electrically = vinCarInfo.back_mirror_electrically_caption;
            GlobalInfo.draft.condition.config_info.dvd = vinCarInfo.dvd_caption;
            GlobalInfo.draft.condition.config_info.park_help = vinCarInfo.park_help_caption;
            GlobalInfo.draft.condition.config_info.reverse_view = vinCarInfo.reverse_view_caption;
            GlobalInfo.draft.condition.config_info.hub_material = vinCarInfo.hub_material_caption;
            GlobalInfo.draft.condition.config_info.front_tire_size = vinCarInfo.front_tire_size;
            GlobalInfo.draft.condition.config_info.rear_tire_size = vinCarInfo.rear_tire_size;
            GlobalInfo.draft.condition.config_info.spare_tire = vinCarInfo.spare_tire_caption;

            saveVinCarInfoDb();
        }
        mContext.startActivity(intent);
        ProgressDialogUtil.dismissProgressDlg();
        clear();
        isCreate = false;
    }

    //更新数据库，立即保存通过vin码获取到的车辆信息
    private void saveVinCarInfoDb() {

        ContentValues values = new ContentValues();

        //保存车型车系信息
        BaseInfo baseInfo = GlobalInfo.draft.base_info;
        values.put(DbHelper.KEY_DRAFT_BASE_INFO, toJson(baseInfo));
        int status_base = baseInfo.getStatus();
        values.put(DbHelper.KEY_DRAFT_BASE_INFO_STATUS, status_base);

        //保存配置信息
        Condition condition = GlobalInfo.draft.condition;
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(GlobalInfo.draft.condition));
        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);



        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values)) {
            GlobalInfo.draft.base_info = baseInfo.clone();
            GlobalInfo.draft.status[Draft.TYPE_BASE_INFO] = status;

            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));
        }
    }


    /**
     * 保存记录
     */
    private void saveRecord(String carPlate, String vin, String carId) {
        GlobalInfo.dbHelper.insertDraf(carPlate, vin, carId);
        GlobalInfo.draft = GlobalInfo.dbHelper.getDraft(carPlate);
        getCarMsgByVin(vin);
    }

    @Override
    public boolean save() {
        return false;
    }

    @Override
    public boolean dataChanged() {
        return false;
    }

    public class ErrorResponse {
        @SerializedName("errorCode")
        int errorCode;
        @SerializedName("errorMessge")
        String errorMessge;
        @SerializedName("data")
        String data;
    }
}
